# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import *
from django.forms import ModelForm
from accounts.models import *
from accounts.forms import * 
#from chitchats.chatting import *
#from chitchats.chitchatLogging import *
#from chitchats.chitchatLogTest import *
#from chitchats.chitchatMongo import *
#from chitchats.chitchatMongoTest import *
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required 
from Internet.chitchatLogging import ChitchatLogger
from django.views.decorators.csrf import csrf_exempt
from django import forms
from django.core.exceptions import ValidationError
from random import randint
import re
import json

logger = ChitchatLogger("view_debug")

class LoginForm(forms.Form):
    user = forms.CharField(required=True, 
                        max_length=15,
                        widget=forms.TextInput(attrs={'placeholder':'用户名'}),
                        error_messages={'required': '用户名不能为空.','max_length':"最多15位"})
    pwd = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.TextInput(attrs={'placeholder':'密码','type':'password'}),
                        error_messages={'required': '密码不能为空.', 'max_length':"最多20位"})
    def clean(self):
        cleaned_data = self.cleaned_data
        user = cleaned_data.get('user')
        PassWord = cleaned_data.get('pwd')
        userID=ChatUser.objects.filter(UserID=user)
        if not userID:
            raise forms.ValidationError('用户不存在!')
        else:
            Valid=authenticate(username=user,password=PassWord)
            if Valid is None:
                raise forms.ValidationError('密码错误!')
        return cleaned_data
        

def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')



class RegisterForm(forms.Form):
    user = forms.CharField(required=True, 
                        min_length=6,
                        max_length=15,
                        error_messages={'required': '用户名不能为空','min_length': "用户名至少6位",'max_length':"用户名最多15位"})
    
    pwd = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.PasswordInput,
                        error_messages={'required':'密码不能为空','max_length':"密码最多20位"})
    pwd2 = forms.CharField(required=False,
                        max_length=20,
                        widget=forms.PasswordInput,)
    nickname = forms.CharField(required=True,
                            max_length=20,
                            error_messages={'required': '昵称不能为空','max_length':'昵称最多20位'})
    email = forms.EmailField(error_messages={'required': '电子邮箱不能为空', 'invalid':'邮箱格式不正确'})
    

    def clean_user(self):
        user = self.cleaned_data.get('user')
        userID=ChatUser.objects.filter(UserID=user)
        if userID:
            raise forms.ValidationError('用户名已经注册!')
        return user

    def clean(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.has_key('pwd') and cleaned_data.has_key('pwd2'):
            pwd = cleaned_data['pwd']
            pwd2 = cleaned_data['pwd2']
            if pwd != pwd2:
                raise forms.ValidationError('二次输入密码不匹配')
        return cleaned_data 
class EditForm(forms.Form):
    
    nickname = forms.CharField(required=True,
                        max_length=20,
                        )
    email = forms.CharField(required=True,
                        max_length=20,
                        )
    note =  forms.CharField(required = False,
                        max_length = 100,
                        )
    def clean(self):
        cleaned_data = self.cleaned_data
        return cleaned_data
class SecurityForm(forms.Form):
    
    pwd = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.PasswordInput,)
    pwd1 = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.PasswordInput,)
    pwd2 = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.PasswordInput,)
    def clean(self):
        if not self.is_valid():
            raise forms.ValidationError(u"所有项都为必填项")
        elif self.cleaned_data['pwd1'] <> self.cleaned_data['pwd2']:
            raise forms.ValidationError(u"两次输入的新密码不一样")
        else:
            cleaned_data = super(SecurityForm, self).clean()
        return cleaned_data


@csrf_exempt
def usercheck(request):
    if request.POST:
        username=request.POST.get('username')
        user=ChatUser.objects.filter(UserID=username)
        if user:
            dic={'info':1}
            data=json.dumps(dic)
            return HttpResponse(data)
        else:
            dic={'info':0}
            data=json.dumps(dic)
            return HttpResponse(data)


@csrf_exempt       
def register(request):
    if request.POST:
    #if  request.is_ajax() and request.method == 'POST':
        objPost = RegisterForm(request.POST)
        ret = objPost.is_valid()
        if ret:
            UserID=str(len(ChatUser.objects.all())+1)
            UserName = objPost.cleaned_data['user']
            PassWord=objPost.cleaned_data['pwd']
            NewUser = User.objects.create_user(username = UserName, password = PassWord)
            ChatUser(Users=NewUser,UserID=UserID,NickName=objPost.cleaned_data['nickname'],UserEmail=objPost.cleaned_data['email']).save()
            request.session['UserID']=UserID
            return HttpResponseRedirect('/Accounts/login/')
        else:
            pass
        return render(request, 'register.html', {'obj1': objPost})
    else:
        if request.session.has_key('UserID'):
            objGet = RegisterForm()
            return render(request, 'register.html', {'obj1': objGet})
        else:
            return HttpResponseRedirect('/Accounts/select/')

@csrf_exempt
def login(request):
    context = {}
    context['Login_active'] = True
    if request.POST:
        objPost = LoginForm(request.POST)
        ret = objPost.is_valid()
        if ret:
            UserID=objPost.cleaned_data['user']
            request.session['UserID']=UserID
            return HttpResponseRedirect('/Accounts/select/')
        else:
            pass
        
        context['obj1'] = objPost
        return render(request,'accountlogin.html', context)
    
    else:	#无请求  
        if not request.session.has_key('UserID'):
            objGet = LoginForm()
            context['obj1'] = objGet
            return render(request,'accountlogin.html', context)
        else:	#session中已有记录
            #return render(request,'accountlogin.html', context)
            return HttpResponseRedirect('/Accounts/select/')
@csrf_exempt
def select(request):
    if not request.session.has_key("UserID"):
        return HttpResponseRedirect("/Accounts/login/")
        #请先登录，再开始聊天
    else:
        UserID = request.session.get('UserID')
        user = ChatUser.objects.get(UserID = UserID)
        username = user.NickName 
        user.Online  = 1
        user.save()
        return render(request, 'select.html',{'username':username})
@csrf_exempt
def index(request):
    objGet = "index" #这里应该去数据库里找到当前user的nickname
    return render(request, 'index.html', {'username': objGet})
@csrf_exempt
def edit(request):
    #objGet = "edit" #这里应该去数据库里找到当前user的nickname
    #return render(request, 'edit.html', {'username': objGet})
    if request.POST:
        form = EditForm(request.POST)
        if form.is_valid():
            UserID = request.session.get('UserID')
            p = ChatUser.objects.get(UserID = UserID)
            if p is not None :
                nickname = request.POST.get('nickname', '')
                email = request.POST.get('email','')
                note = request.POST.get('note','')
                p.NickName = nickname
                p.UserEmail = email
                p.Note = note
                p.save()
                p = ChatUser.objects.get(UserID = UserID)
                logger.log.warning(p)
                return HttpResponseRedirect('/Accounts/select/')
            else:
                return render(request,'edit.html' , {'obj1': form,})
        else:
            return render(request,'edit.html', {'obj1': form,})
    else:
        objGet = EditForm()
        return render(request, 'edit.html', {'obj1': objGet})
@csrf_exempt
def security(request):
    #objGet = "security" #这里应该去数据库里找到当前user的nickname
    #return render(request, 'security.html', {'username': objGet})
    if request.POST:
        form = SecurityForm(request.POST)
        if form.is_valid():
            UserID = request.session.get('UserID')
            p = ChatUser.objects.get(UserID = UserID)
            oldpassword = request.POST.get('pwd', '')
            if p is not None :
                newpassword = request.POST.get('pwd1', '')
                p.Users.set_password (newpassword)
                p.Users.save()
                p = ChatUser.objects.get(UserID = UserID)
                logger.log.warning(p)
                request.session.pop('UserID')
                return HttpResponseRedirect('/Accounts/login/')
            else:
                return render(request,'security.html' , {'obj1': form,})
        else:
            return render(request,'security.html', {'obj1': form,})
    else:
        objGet = SecurityForm()
        return render(request, 'security.html', {'obj1': objGet})
       


@csrf_exempt
def main(request):
    #处理请求
    #返回页面
    objGet = "main"
    return render(request, 'main.html', {'username': objPost})

@csrf_exempt
def logout(request):
    if request.session.has_key('UserID'):
        UserID = request.session.get('UserID')
        user = ChatUser.objects.get(UserID = UserID)
        user.Online = 0
        user.save()
        request.session.pop('UserID')
    return HttpResponseRedirect('/Accounts/login/')
@csrf_exempt
def startchat(request):
    if not request.session.has_key("UserID"):
        return HttpResponseRedirect("/Accounts/login/")
        #请先登录，再开始聊天
    else:
        num =len(ChatUser.objects.filter(Online = 1))
        UserID = request.session.get('UserID')
        user = ChatUser.objects.get(UserID = UserID)
        username = user.NickName
        if num < 2:
            error = "没有其他的在线用户"
            return render(request, 'select.html',{'username':username,'error':error}) 
        else:
            user = ChatUser.objects.filter(Online =1)
            last = num - 1
            uid1 = int(UserID)
            while True:
                rand = randint(0,last)
                chatter = ChatUser.objects.filter(Online =1)[rand]
                uid2 = chatter.UserID
                if uid1 != uid2:
                    break
            error = uid2
        return render(request, 'select.html',{'username':username,'user':uid1,'chat':uid2})

